var app = getApp();
var ux = require('../lib/ux.js');
var QQMapWX = require('../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    authDZs:true,
    shuff:[],
    obj:{},
    list:[],
    topUrl:"/api/Merchant/getHomeScorllImgs.do",
    action: "/api/banrd/banrdList.do",
    submit: "{{submit}}",
    options:{},
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'B5WBZ-NBAHJ-MJQFY-F4RWO-MPNOV-NNBQC' //这里自己的key秘钥进行填充
    });
    console.log("ddddddddd")
    this.setData({
      options:options
    })
    var self = this;
    if (wx.getStorageSync("authDZs")) {
      this.setData({
        authDZs: false
      })
    }
    console.log(JSON.stringify(options));
    ux.loginNew(options, function (res) {
      if (self.data.action) {
        wx.showLoading({
          title: '加载中....',
        })
        console.log(JSON.stringify(self.data.action));
        ux.request(self.data.action, options, function (protocol) {
          self.setData(protocol.data);
          wx.setNavigationBarTitle({
            title: '品牌选择',
          })
        });
        ux.request(self.data.topUrl, {}, function (protocol) {
          wx.hideLoading();
          console.log(JSON.stringify(protocol))
          self.setData({
            shuff: protocol.data.obj.shuff ? protocol.data.obj.shuff.split(",") : []
          })
        });

      }
    })
    self.setData({
      userInfo: wx.getStorageSync("userInfo")
    })
  },
  authDZ:function(){
    wx.showLoading({
      title: '授权地理位置信息',
      mask:true
    })
    this.getUserLocation();
  },
  onForm: function (event) {
    if (this.data.submit) {
      var $this = this;
      var dataset = event.currentTarget.dataset;
      ux.request(this.data.submit, event.detail.value, function (protocol) {
        if (protocol.success) {
          if (dataset.url) {
            wx.redirectTo({ url: dataset.url });
          }
        }
      }, true);
    }
  },

  onTap: function (event) {
    var dataset = event.currentTarget.dataset;
    var data = this.data;
    if (dataset.key && dataset.val) {
      data[dataset.key] = dataset.val;
    }
    this.setData(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // /**
  //    * 用户点击右上角分享
  //    */
  // onShareAppMessage: function () {
  //   var self = this;
  //   wx.showShareMenu({
  //     withShareTicket: true
  //   })
  //   var shareObj = {
  //     title: wx.getStorageSync("pingtai").coverTitle,
  //     imageUrl: wx.getStorageSync("pingtai").coverImg,
  //     path: '/pages/brandSelect?otherId=' + wx.getStorageSync("userInfo").id,
  //     success: function (res) {
  //       console.log(JSON.stringify(res));
  //     },
  //     fail: function () {
  //       wx.showToast({
  //         title: '转发失败',
  //       })
  //     }
  //   }
  //   return shareObj;
  // },
  gotoHome: function (event) {
    var dataset = event.currentTarget.dataset;
    var id = dataset.id;
    wx.setStorageSync("banrd", this.data.list[dataset.index]);
    wx.setStorageSync("banrdId", id);
    wx.reLaunch({
      url: '/pages/member/tab1/sugarSpice?id='+id,
    })
  },
  applyBanrd:function(){
    wx.navigateTo({
      url: '/pages/member/tab1/brand/brandJoin',
    })
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },
  getUserLocation: function () {
    wx.showLoading({
      title: '加载中...',
    })
    let vm = this;
    wx.getSetting({
      success: (res) => {
        wx.hideLoading();
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {

          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        wx.setStorageSync("latitude", latitude);
        wx.setStorageSync("longitude", longitude);
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res) + "错误")
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let province = res.result.ad_info.province;
        let city = res.result.ad_info.city;
        wx.setStorageSync("province", province);
        wx.setStorageSync("city", city);
        wx.setStorageSync("authDZs", true);
        vm.setData({
          authDZs: false
        })
        let district = res.result.ad_info.district;
        wx.setStorageSync("district", district);
        vm.setData({
          province: province,
          city: city,
          latitude: latitude,
          longitude: longitude,
          district: district
        })
        setTimeout(function () {
          wx.hideLoading();
        }, 3000);

      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  }
})
